package com.resource.spring.aspectj;

import cn.hutool.json.JSONUtil;
import com.resource.constant.OfficeApiConstants;
import com.resource.spring.ApplicationUtils;
import com.resource.spring.model.Log;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 操作日志记录处理
 * @Author: xianggaoxiong
 * @Date: 15:54 2020/9/27
 */
@Aspect
@Component
@Slf4j
public class LogAspect {

    /**
     * 配置织入点
     */
    @Pointcut("execution(public * com.resource..*.*Controller.*(..))")
    public void logPointCut() {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     * @param ret       返回值
     */
    @AfterReturning(returning = "ret", pointcut = "logPointCut()")
    public void doAfterReturning(JoinPoint joinPoint, Object ret) {
        handleLog(joinPoint, ret, null);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, null, e);
    }

    protected void handleLog(final JoinPoint joinPoint, final Object ret, final Exception e) {
        try {
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            String actionMethod = className + "." + methodName + "()";
            HttpServletRequest request = ApplicationUtils.getRequest();
            printLog((Long) request.getAttribute(OfficeApiConstants.API_BEGIN_TIME),
                    request.getParameterMap(),
                    request.getAttribute(OfficeApiConstants.API_REQUEST_BODY),
                    (String) request.getAttribute(OfficeApiConstants.API_REQURL),
                    actionMethod,
                    request.getMethod(),
                    ret);
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    public static void printLog(Long beiginTime, Map<String, String[]> parameterMap, Object requestBody, String url, String actionMethod, String method, Object object) {
        String runTime = (beiginTime != null ? System.currentTimeMillis() - beiginTime : 0) + "ms";
        Log logInfo = Log.builder()
                //查询参数
                .parameterMap(parameterMap)
                //请求体r
                .requestBody(requestBody)
                //请求路径
                .url(url)
                //控制器方法
                .actionMethod(actionMethod)
                //请求方法
                .method(method)
                .runTime(runTime)
                .result(object)
                .build();
        String logJson = JSONUtil.toJsonStr(logInfo);
        log.info(logJson);
    }

}
